package cn.aaalei.service.impl;

import cn.aaalei.pojo.AdminInfo;
import cn.aaalei.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AdminService adminService;

    /**
     * 逻辑: 通过名称从数据库中提取用户密码及status 将其封装 传给上层处理验证
     * 想当于此类是一个获取数据的方法 处理方法被框架封装了
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (adminService==null) {
            throw new RuntimeException("system服务为启动或启动失败");
        }
        List<AdminInfo> admins = adminService.findList(username);
        if(admins.size()==0){
            return null;
        }
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return new User(username,admins.get(0).getPassword(),grantedAuthorities);
    }
}
